import platform

import bs4
import requests
from bs4 import BeautifulSoup
import os


def searchAndFetch(word: str):
    search_url: str = 'https://baike.baidu.com/api/searchui/suggest?enc=utf8&wd=' + word
    response = requests.get(search_url)

    if response.status_code == 200:
        # 获取JSON响应
        json_data = response.json()

        list_value = json_data.get('list')

        for lemma in list_value:
            lemmaId = lemma.get('lemmaId')
            lemmaTitle = lemma.get('lemmaTitle')
            fetch(lemmaId, lemmaTitle)


def fetch(lemma_id: int, lemma_title: str):
    fetch_url = 'https://baike.baidu.com/item/' + lemma_title + '/' + str(lemma_id)
    response = requests.get(fetch_url)

    if response.status_code == 200:
        soup = BeautifulSoup(response.text, 'html.parser')

        text: str = ''
        writeFirstPara: bool = True

        paras = soup.find_all(class_=lambda c: c and c.startswith('para_'))

        for para in paras:
            handledPara = handlePara(para)
            if handledPara != '':
                if writeFirstPara:
                    text += handledPara
                    writeFirstPara = False
                else:
                    os_name = platform.system()
                    if os_name == "Windows":
                        text = text + '\r\n' + handledPara
                    elif os_name == "Linux":
                        text = text + '\n' + handledPara
        save(text, lemma_title)

    else:
        print('请求失败')


def handlePara(para) -> str:
    handledPara: str = ''
    pieces = para.contents
    for piece in pieces:
        piece_inner = piece.contents[0]
        if isinstance(piece_inner, bs4.element.NavigableString):
            handledPara += piece_inner
        elif isinstance(piece_inner, bs4.element.Tag) and isinstance(piece_inner.contents[0],
                                                                     bs4.element.NavigableString):
            handledPara += piece_inner.contents[0]
    return handledPara


def save(text: str, title: str):
    current_directory = os.getcwd()
    file_path = os.path.join(current_directory, title + ".txt")
    print(file_path)
    with open(file_path, "w", encoding="utf-8") as file:
        file.write(text)


if __name__ == '__main__':
    searchAndFetch('农业')
